﻿using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Xml.Linq;

namespace System
{
    public class ThumbnailHelper
    {
        protected readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static string themePath;

        public static event Action<string, BitmapSource> BitmapSourceChanged;

        public static BitmapSource GetBitmapSourceByFilePath(string filePath)
        {
            if (filePath.IsNullOrWhiteSpace() || !FileHelper.IsExistFile(filePath))
                return null;

            var tempImage = ImagePathToBitmapSource(filePath);
            return tempImage;
        }

        public static BitmapSource ConvertBitmapSource(byte[] bytes)
        {
            BitmapSource BitmapSource = null;
            if (bytes?.Any() == true)
            {
                using (var stream = new MemoryStream(bytes))
                {
                    BitmapSource = ConvertBitmapSource(new MemoryStream(bytes));
                }
            }
            return BitmapSource;
        }

        public static BitmapSource ConvertBitmapSource(Stream stream)
        {
            BitmapImage BitmapSource = new BitmapImage();
            if (stream != null)
            {
                BitmapSource.BeginInit();
                BitmapSource.StreamSource = stream;
                BitmapSource.CacheOption = BitmapCacheOption.OnLoad;
                BitmapSource.EndInit();
            }
            else
            {
                BitmapSource = null;
            }
            return BitmapSource;
        }

        /// <summary>
        /// 缩略图颜色反转成灰色
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static BitmapSource ConvertToGrayscale(BitmapSource source)
        {
            if (source is null)
                return null;
            int sourcePixel = source.PixelWidth > source.PixelHeight ? source.PixelWidth : source.PixelHeight;

            var stride = (sourcePixel * source.Format.BitsPerPixel + 7) / 8;
            var pixels = new byte[stride * sourcePixel];
            source.CopyPixels(pixels, stride, 0);
            for (int i = 0; i < pixels.Length; i += 4)
            {
                // this works for PixelFormats.Bgra32
                var blue = pixels[i];
                var green = pixels[i + 1];
                var red = pixels[i + 2];
                var gray = (byte)(0.2126 * red + 0.7152 * green + 0.0722 * blue);
                pixels[i] = gray;
                pixels[i + 1] = gray;
                pixels[i + 2] = gray;
            }
            return BitmapSource.Create(
                source.PixelWidth, source.PixelHeight,
                source.DpiX, source.DpiY,
                source.Format, null, pixels, stride);
        }

        public static void RaiseDCMBitmapSourceChanged(string id, BitmapSource tempImage)
        {
            AsyncActionHelper.RunTask(() => BitmapSourceChanged?.Invoke(id, tempImage));
        }

        public static string GetThumbnailImagePath(string id)
        {
            return $@"{AppDomain.CurrentDomain.BaseDirectory}Temp\Icon\{id}.jpg";
        }

        public static string GetThemePath()
        {
            if (themePath.IsNullOrWhiteSpace())
            {
                string theme = ConfigurationManager.AppSettings["Theme"];
                themePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes", theme);
            }
            return themePath;
        }

        private static BitmapSource ImagePathToBitmapSource(string filePath)
        {
            BitmapSource tempImage = null;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                tempImage = ConvertBitmapSource(buffer);
            }
            return tempImage;
        }
    }
}
